package com.foreknow.controller;

import com.foreknow.bean.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Servlet:表示服务器端的小应用程序，在MVC模型中为控制器(Controller)
 * 主要用作用：可以处理客户端的请求以及页面的转发
 * 类一定要继承HttpServlet
 * 我们需要重写
 * 1. doGet(HttpServletRequest req, HttpServletResponse resp)
 * 1.1 如果客户端向服务器端发送的是get请求(a标签)，那么servlet中就会自动调用doGet方法处理请求
 * 2. doPost(HttpServletRequest req, HttpServletResponse resp)
 * 2.1 如果客户端向务器端发送的是post请求(表单method属性为post)那么servlet中就会自动调用doPost方法处理请求
 *
 */
public class FirstServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        //客户端向服务器端请求的编码格式设置为utf-8
        //        req.setCharacterEncoding("utf-8");
        //通过response对象获取到PrintWriter打印流
        PrintWriter out = resp.getWriter();
        //获取到表单的请求参数
        String name = req.getParameter("username");
        String pass = req.getParameter("pass");
        //将用户名保存到session对象中
        HttpSession session = req.getSession();
        String contextPath = req.getContextPath();
        //调用Service的方法
        AdminService service = new AdminServiceImpl();
        Admin admin = service.isValidate(name,pass);
        //向session中保存数据
        session.setAttribute("username",admin.getAdminName());
        if(admin!=null){
//            out.println("<a href='/WebCMSSystem/user/get'>query guestbook info</a>");
            //请求转发
//            req.getRequestDispatcher("/user/get").forward(req,resp);
            //重定向
            resp.sendRedirect(req.getContextPath()+"/user/manager?q=list");
        }else {
            out.println("error......");
        }
    }
}
